<?php

abstract class protocol_module extends module {
	public $me, $state = 0;
	protected $connection;
	
	abstract public function connect($host, $port, $password, $parameters = array());
	abstract public function disconnect();
	abstract public function send($input);
	abstract public function receive();
	public function message_parser(basic &$source, basic &$target, $parameters, $type) {
		if ($target instanceof user) {
			$this->user_message_parser($source, $target, $parameters, $type);
		} elseif ($target instanceof channel) {
			$this->channel_message_parser($source, $target, $parameters, $type);
		} elseif ($target instanceof server) {
			$this->server_message_parser($source, $target, $parameters, $type);
		} else {
			throw new Exception("Unknown basic type implemented for message parser",024);
		}
	}
	abstract public function user_message_parser(basic &$source, user &$target, $parameters, $type);
	abstract public function channel_message_parser(basic &$source, channel &$target, $parameters, $type);
	abstract public function server_message_parser(basic &$source, server &$target, $parameters, $type);
	
	public function __construct(server &$me) {
		$this->me =& $me;
		//$GLOBALS['protocol'] =& $this;
		$this->name =& $this->me->name;
		$this->me->protocol =& $this;
	}
	static public function make_basic (&$subject) {
		if ($subject instanceof basic) return false;
		if (!$subject) throw new Exception("empty subject provided");
		$sbj = $subject;
		if (is_numeric($sbj)) {
			$subject = (array_key_exists((int)$sbj, $GLOBALS['servers_by_numeric']) ? $GLOBALS['servers_by_numeric'][(int)$sbj] : null);
		} elseif (is_numeric($sbj{0})) {
			$subject = (array_key_exists($sbj, $GLOBALS['basics']) ? $GLOBALS['basics'][$sbj] : null);
		} elseif ($sbj{0} == '#') {
			if (array_key_exists(strtolower($sbj), $GLOBALS['channels'])) {
				$subject = $GLOBALS['channels'][strtolower($sbj)];
			}
		} elseif (strpos($sbj,'@') !== false) {
			list($sbj, $host) = explode('@', $sbj, 2);
			if (strpos($sbj, '!') !== false) {
				list($sbj, $username) = explode('!', $sbj, 2);
			}
		} elseif (strpos($sbj,'.') !== false) {
			if (array_key_exists(strtolower($sbj),$GLOBALS['servers'])) {
				$subject = $GLOBALS['servers'][strtolower($sbj)];
			}
		}
		if (array_key_exists(strtolower($sbj),$GLOBALS['users'])) {
			$sbj =& $GLOBALS['users'][strtolower($sbj)];
			if (isset($host) and abs(strcasecmp($host,$sbj->host))
			and abs(strcasecmp($host,$sbj->fakehost))) {
				//devnull
			}
			elseif (isset($username) and abs(strcasecmp($username,$subject->username))) {
				//devnull
			} else {
				$subject = $sbj;
			}
		}
		return ($subject instanceof basic);
	}
}
?>